define(function(require, exports){
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view  = require('@base/view');

	// 地域分析
	var Region = view.container.extend({
		init:function(config){

			// 汇总子表格
			var overview_subgrid = config.param && config.param.overview_subgrid;
			this.$overview_subgrid = {};
			if(overview_subgrid)
			{
				this.$overview_subgrid = {
					'get_all_info': 1,
					'ListAll':1,
					'showChildren':1,
					'overview_subgrid':1
				}
			}

			config = pubjs.conf(config, {
				'class':'M-chartAdv P-region',
				'url': 'region/list',
				'param': util.extend(
					{
						metrics:["impressions","clicks","click_rate"],
						order: "impressions|-1,clicks|-1"
					},
					this.$overview_subgrid
				)
			});

			// 如果父级为落地页，指标组中要去掉前端类的指标
			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'cost': null, 'front': null}
				});
			}

			this.$current = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var c = this.getConfig();

			this.append([
				// 日期控件
				'<div class="M-chartAdvDateBox" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				// 图表切换
				'<div class="P-regionButtonGroup clear mb20" pub-name="mode" pub-mod="@base/common/input.buttonGroup" />',
				'<div class="P-regionChart pt30 clear">',
					// 趋势图
					'<div class="P-regionChartMain" pub-name="chart" pub-mod="modules/geo.base" />',
					// 说明提示
					'<div class="P-regionTip" pub-name="tip" pub-mod="modules/geo.tip" />',
				'</div>',
				// 表格
				'<div class="P-regionGrid clear" pub-name="grid" pub-mod="@base/highGrid.base" />'
			].join(''));

			var param = util.extend(
				pubjs.getDate(),
				c.param,
				{
					'no_limit': true
				}
			);

			var gridParam = util.extend(
				{}
				,c.syncParentGridParam ? c.param : {} // 需要同步的时候同步父表格
				,{
					viewtb: 0,
					order: 'impressions|-1',
					condition: c.param.condition
				}
				,this.$overview_subgrid
			);
			// 汇总的删除默认指标
			if(c.syncParentGridParam){
				delete gridParam.metrics;
			}

			var config = {
				'mode': {
					"selected": 1, // 0 图，1 表
					"items":[LANG("图"),LANG("表")]
				},
				'chart': {
					param: param,
					url: c.url,
					reqType: 'websocket',
					autoLoad: false
				},
				'tip':{
					autoShow: false
				},
				'grid': {
					url: c.url,
					param: gridParam,
					auto_load:false,
					cols: [
						{type:"id"},
						{name:'region_name',text: LANG('地区'), render: this.renderName}
					],
					// metrics: c.metricGroup,
					default_metrics : [
						"impressions","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost"
					],
					tab: c.tab,
					hasPager: true,
					hasSubGrid: false,
					hasRefresh: true,
					reqType: 'websocket',
					gridName: c.gridName || 'region',
					gridNameSuffix: c.gridName ? c.gridNameSuffix : '',
					hasSearch: false,
					hasFilter: false,
					hasDateRange: false
					// wrapperClass: 'G-frameBodyContainer'
				},
				'date': {
					'pos': 'bR',
					'broadcast': false
				}
			};

			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function(){
			this.load();
		},
		//地图准备事件，完成后渲染列表
		onGeoReady:function(ev){
			this.hideLoading();
			this.renderList();
		},
		//top10地区列表渲染函数
		renderList:function(){
			var el = this.$el.find('.P-regionChart');
			el.find('.P-regionTop10').remove();

			var data= this.$.chart.getData();
			var len = Math.min(10,data.length);
			var html = [
				'<div class="P-regionTop10 M-tableList" >',
				'<table class="P-regionTop10Table"><thead><tr>',
				'<td>'+LANG("序号")+'</td>',
				'<td>'+LANG("名称")+'</td>',
				'<td>'+LANG("展示量")+'</td>',
				'<td>'+LANG("点击量")+'</td>',
				'<td>'+LANG("点击率")+'</td>',
				'</tr></thead>'
			].join('');

			var htm,cur;
			if(len>0){
				for(var i=0;i<len;i++){
					cur = data[i];
					htm='<tr>';
					htm+='<td>'+(i+1)+'</td>';
					htm+='<td>'+cur.region_name+'</td>';
					htm+='<td>'+cur.impressions+'</td>';
					htm+='<td>'+cur.clicks+'</td>';
					htm+='<td>'+cur.click_rate+'</td>';
					htm+='</tr>';
					html+=htm;
				}
			} else {
				html+='</thead><tr><td colspan="5" style="text-align:center">'+LANG("没有数据")+'</td></tr>';
			}
			html+='</table></div>';
			el.append($(html));
		},
		renderName: function(i, val, data, con){
			var html = $([
				'<div>',
					'<img class="fl" src="/resources/images/geo/'+(data.country_icon||'unknown')+'.png" />',
					'<span class="fl ml10">'+data.country_name+' '+val+'</span>',
				'</div>'
			].join('')).width(240);

			html.find('span').css('line-height', '16px');

			return html;
		},
		load: function(){
			var mode = +this.$.mode.getData();
			var el = this.$el;
			el.find('.P-regionChart').toggle(mode === 0);
			el.find('.P-regionGrid').toggle(mode === 1);

			if(mode === 0){
				this.showLoading();
				this.$.chart.load();
			}

			if(mode === 1){
				this.$.grid.reload();
			}
			return false;
		},
		// 响应日期条事件
		onDateRangeChange: function(ev){
			if(!this.getDOM().is(':visible')){
				return false;
			}

			// 设置日期参数
			var param = ev.param.nowTimestamp;
			this.$.grid.setParam(param);
			this.$.chart.setParam(param);
			this.load();

			return false;
		},
		onSubgridParam: function(ev){
			var self = this;
			var c = self.getConfig();
			// 汇总子表格时，需要同步更新
			if(c.syncParentGridParam){
				var param = ev.param.data;
				self.$.grid.setParam(param);
				self.$.chart.setParam(param);
				// self.load(); // 暂时不自动加载，只设参数，需要手动重新load
			}
		},
		// 图表切换
		onChangeButton: function(ev){
			this.load();
			return false;
		},
		//地图hover处理事件
		onMapHover:function(e){
			if (this.$current && this.$current ===e.param.data){
				return;
			}
			var param = e.param,html='',data = this.$.chart.getData(param.data);
			this.$current = param.data;
			if(data&&data.region_name){
				html+='<strong>'+data.region_name+'</strong><br/>';
				html+=LANG('展示量: %1', data.impressions)+'<br/>';
				html+=LANG('点击量: %1', data.clicks)+'<br/>';
				html+=LANG('点击率: %1', data.click_rate)+'<br/>';
			}
			var pos = this.$el.offset();
			param.data = html;
			param.x -= pos.left;
			param.y -= pos.top;
			if(param.data){
				this.$current = null;
				// this.$.chart.removeSelected();
				var tip = this.get('tip');
				tip.update({location: param}).setData(param.data).show();
			}
		},
		// //tip隐藏后触发的事件，当前显示的省份名字设为null
		onTipHided:function(){
			this.$current = null;
			this.$.chart.removeSelected();
		},
		// 解析子表格的Condition配置，用于子表格过滤指标组
		parseSubsCondition: function(config){
			var c = config.get();
			var ret = [];
			var param = c.param;
			var condition = '';

			if(param && param.condition){
				// 先解析字符串
				condition = JSON.parse(param.condition);
				util.each(condition, function(item, idx){
					if(item && util.isObject(item)){
						for(var i in item){
							var key = i;
							if(key){
								if (key.slice(-3) === '_id'){
									ret.push(key.slice(0,-3));
								}else {
									ret.push(key);
								}
							}
						}
					}
				});
			}
			// 返回condition的key数组
			return ret;
		}
	});
	exports.base = Region;


});